{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "wo_14MMa-BA1"
      },
      "source": [
        "# Byte-Pair Encoding tokenization"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "FHtvAVBK-BA8"
      },
      "source": [
        "Install the Transformers, Datasets, and Evaluate libraries to run this notebook."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "关于BPE算法的文档描述： https://huggingface.co/learn/nlp-course/en/chapter6/5?fw=pt"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "CHxJq2wg-BA9"
      },
      "outputs": [],
      "source": [
        "!pip install datasets evaluate transformers[sentencepiece]"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "oLQ14uQ7-BA_"
      },
      "outputs": [],
      "source": [
        "corpus = [\n",
        "    \"This is the Hugging Face Course.\",\n",
        "    \"This chapter is about tokenization.\",\n",
        "    \"This section shows several tokenizer algorithms.\",\n",
        "    \"Hopefully, you will be able to understand how they are trained and generate tokens.\",\n",
        "]"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "Cgg3YzuM-BBA"
      },
      "outputs": [],
      "source": [
        "from transformers import AutoTokenizer\n",
        "\n",
        "tokenizer = AutoTokenizer.from_pretrained(\"gpt2\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "GPT 模型通常使用 UTF-8 编码\n",
        "GPT 系列（如 GPT-2）通常采用 UTF-8 编码 + BPE 分词，完全支持多语言；\n",
        "UTF-8 是目前最常用的文本编码，也更适合网络和跨平台应用。\n",
        "UTF-8 是一种可变长编码，可以编码所有 Unicode 字符，包括：\n",
        "- 拉丁字母（英文、德语等）\n",
        "- 汉字（中文）\n",
        "- 假名（日本语）\n",
        "- 韩文\n",
        "- 阿拉伯文\n",
        "- Emoji 等\n",
        "\n",
        "它是全球使用最广泛的 Unicode 编码方式，多语言支持完全没有问题。\n",
        "\n",
        "1. 首字节的高位模式用于表示“总长度”\n",
        "UTF-8 使用每个字符的首字节前缀来表示这个字符使用了多少个字节进行编码：\n",
        "\n",
        "字节数\t首字节的二进制前缀\t可编码范围（十进制）  \n",
        "1 字节\t0xxxxxxx\t0～127（ASCII）  \n",
        "2 字节\t110xxxxx\t128～2047  \n",
        "3 字节\t1110xxxx\t2048～65535  \n",
        "4 字节\t11110xxx\t65536～1114111（即 0x10FFFF）  \n",
        "\n",
        "每个非首字节都以 10xxxxxx 开头，称为 continuation byte。  "
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "首先进行预分词，基本上是按照空格进行切分，空格分配到后续紧跟的单词上  \n",
        "在 GPT-2 分词器中，Ġ（实际是 Unicode 字符 U+0120，叫作 Latin Capital Letter G with dot above）用来表示 一个空格（或词的边界）。\n",
        "示例说明：\n",
        "- 'This' → 没有 Ġ，说明它是句子的起始词，前面没有空格。\n",
        "- 'Ġis' → 前面有 Ġ，说明原始字符串是 \" is\"（有一个空格）。\n",
        "- 'Ġthe' → 对应原始文本 \" the\"。\n",
        "- 'ĠHugging' → 对应 \" Hugging\"。\n",
        "也就是说，GPT-2 分词器会把空格信息编码进 token 本身，而不是单独作为一个 token 保留。  \n",
        "\n",
        "\n",
        "下面的代码在分词的基础上进一步统计单词出现的频率"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "kV-FHHs9-BBB",
        "outputId": "70dd1357-9958-4186-c2ee-22652bb129c6"
      },
      "outputs": [],
      "source": [
        "from collections import defaultdict\n",
        "\n",
        "word_freqs = defaultdict(int)\n",
        "\n",
        "for text in corpus:\n",
        "    words_with_offsets = tokenizer.backend_tokenizer.pre_tokenizer.pre_tokenize_str(text)\n",
        "    new_words = [word for word, offset in words_with_offsets]\n",
        "    for word in new_words:\n",
        "        word_freqs[word] += 1\n",
        "\n",
        "print(word_freqs)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "进一步将单词切分成没有重复的字符集合，且按字符顺序进行排序。"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "_KETHTpw-BBD",
        "outputId": "04026d28-c2bf-4d1e-c74a-a59a8ad9eea2"
      },
      "outputs": [],
      "source": [
        "alphabet = []\n",
        "\n",
        "for word in word_freqs.keys():\n",
        "    for letter in word:\n",
        "        if letter not in alphabet:\n",
        "            alphabet.append(letter)\n",
        "alphabet.sort()\n",
        "\n",
        "print(alphabet)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": []
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "y4B_eyk6-BBE"
      },
      "outputs": [],
      "source": [
        "# 添加特殊token\n",
        "vocab = [\"<|endoftext|>\"] + alphabet.copy()"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "D40VbcGU-BBE"
      },
      "outputs": [],
      "source": [
        "# 对原先的每一个单词进行字符切分形成单词作为key和对应的字符列表作为value的词典splits\n",
        "splits = {word: [c for c in word] for word in word_freqs.keys()}"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "0I4KHBfT-BBF"
      },
      "outputs": [],
      "source": [
        "# 统计相邻的字符出现的频率，为所有词频字典中unique的单词中相邻的字符对在不同单词中出现（对应出现的次数为freq）的总体统计\n",
        "def compute_pair_freqs(splits):\n",
        "    pair_freqs = defaultdict(int)\n",
        "    for word, freq in word_freqs.items():\n",
        "        split = splits[word]\n",
        "        if len(split) == 1:\n",
        "            continue\n",
        "        for i in range(len(split) - 1):\n",
        "            pair = (split[i], split[i + 1])\n",
        "            pair_freqs[pair] += freq\n",
        "    return pair_freqs"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "GOYEaiBO-BBF",
        "outputId": "875e5df0-4c1d-4798-baad-6e93ebe91dd0"
      },
      "outputs": [],
      "source": [
        "# 将其前面5个字符对打印出来\n",
        "pair_freqs = compute_pair_freqs(splits)\n",
        "\n",
        "for i, key in enumerate(pair_freqs.keys()):\n",
        "    print(f\"{key}: {pair_freqs[key]}\")\n",
        "    if i >= 5:\n",
        "        break"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "5bVwpon1-BBG",
        "outputId": "ab3d7e03-cb96-4d1a-d90b-898d35a2acb9"
      },
      "outputs": [],
      "source": [
        "# 获取频率最高的相邻字符对\n",
        "best_pair = \"\"\n",
        "max_freq = None\n",
        "\n",
        "for pair, freq in pair_freqs.items():\n",
        "    if max_freq is None or max_freq < freq:\n",
        "        best_pair = pair\n",
        "        max_freq = freq\n",
        "\n",
        "print(best_pair, max_freq)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "4sk1Z1PM-BBG"
      },
      "outputs": [],
      "source": [
        "# 将最高的相邻字符对进行合并并放入到词汇表中\n",
        "merges = {(\"Ġ\", \"t\"): \"Ġt\"}\n",
        "vocab.append(\"Ġt\")"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "HWDrEtk5-BBH"
      },
      "outputs": [],
      "source": [
        "# 将合并的结果更新到单词及其切分结果的字典里\n",
        "def merge_pair(a, b, splits):\n",
        "    for word in word_freqs:\n",
        "        split = splits[word]\n",
        "        if len(split) == 1:\n",
        "            continue\n",
        "\n",
        "        i = 0\n",
        "        while i < len(split) - 1:\n",
        "            if split[i] == a and split[i + 1] == b:\n",
        "                split = split[:i] + [a + b] + split[i + 2 :]\n",
        "            else:\n",
        "                i += 1\n",
        "        splits[word] = split\n",
        "    return splits"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "4H0ySaUj-BBH",
        "outputId": "d4a863ea-0d58-4291-b377-687b19ca988e"
      },
      "outputs": [],
      "source": [
        "splits = merge_pair(\"Ġ\", \"t\", splits)\n",
        "print(splits[\"Ġtrained\"])"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "SkcV2iwU-BBH"
      },
      "outputs": [],
      "source": [
        "#合并最高的相邻的现有词汇，并更新到词汇表里，不断持续这个过程支持达到词汇表定义的长度\n",
        "vocab_size = 50\n",
        "\n",
        "while len(vocab) < vocab_size:\n",
        "    pair_freqs = compute_pair_freqs(splits)\n",
        "    best_pair = \"\"\n",
        "    max_freq = None\n",
        "    for pair, freq in pair_freqs.items():\n",
        "        if max_freq is None or max_freq < freq:\n",
        "            best_pair = pair\n",
        "            max_freq = freq\n",
        "    splits = merge_pair(*best_pair, splits)\n",
        "    merges[best_pair] = best_pair[0] + best_pair[1]\n",
        "    vocab.append(best_pair[0] + best_pair[1])"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "Sv7YqPnl-BBH",
        "outputId": "8d22ee93-17b1-4300-a538-8f838a7afd14"
      },
      "outputs": [],
      "source": [
        "print(merges)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "ww16AibM-BBI",
        "outputId": "106516d1-0d3a-48a1-d8df-7422b44b8983"
      },
      "outputs": [],
      "source": [
        "print(vocab)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "MidgLAnk-BBI"
      },
      "outputs": [],
      "source": [
        "# 基于新的词汇表，将文本进行分词的并进行输出\n",
        "def tokenize(text):\n",
        "    pre_tokenize_result = tokenizer._tokenizer.pre_tokenizer.pre_tokenize_str(text)\n",
        "    pre_tokenized_text = [word for word, offset in pre_tokenize_result]\n",
        "    splits = [[l for l in word] for word in pre_tokenized_text]\n",
        "    # 对于所有的merge生成的新的词汇，更新每个单词的切分结果\n",
        "    for pair, merge in merges.items():\n",
        "        for idx, split in enumerate(splits):\n",
        "            i = 0\n",
        "            while i < len(split) - 1:\n",
        "                if split[i] == pair[0] and split[i + 1] == pair[1]:\n",
        "                    split = split[:i] + [merge] + split[i + 2 :]\n",
        "                else:\n",
        "                    i += 1\n",
        "            splits[idx] = split\n",
        "\n",
        "    return sum(splits, []) #用是将 splits 中的所有子列表拼接成一个单一的列表"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "zJXwTjvH-BBI",
        "outputId": "c92c1c6f-3fd1-431c-be5d-9dfe945c0f59"
      },
      "outputs": [],
      "source": [
        "tokenize(\"This is not a token.\")"
      ]
    }
  ],
  "metadata": {
    "colab": {
      "name": "Byte-Pair Encoding tokenization",
      "provenance": []
    },
    "kernelspec": {
      "display_name": "base",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "codemirror_mode": {
        "name": "ipython",
        "version": 3
      },
      "file_extension": ".py",
      "mimetype": "text/x-python",
      "name": "python",
      "nbconvert_exporter": "python",
      "pygments_lexer": "ipython3",
      "version": "3.13.5"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}
